<!-- 商品管理 -->
<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.code"
            placeholder="请输入商品编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :icon="Search">
            搜索
          </el-button>
          <el-button @click="resetHandleQuery" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex-x-between">
          <div>
            <el-button type="success" @click="handleOpenDialog()" :icon="Plus">
              新增
            </el-button>
            <el-button type="danger" :icon="Delete">删除</el-button>
          </div>
          <div>
            <el-button class="ml-3" @click="handleOpenDialog">导入</el-button>

            <el-button class="ml-3" @click="handleOpenDialog">导出</el-button>
          </div>
        </div>
      </template>

      <el-table
        ref="dataTableRef"
        :data="pageData"
        highlight-current-row
        border
      >
        <el-table-column type="selection" width="55px" align="center" />
        <el-table-column label="商品名称" prop="name" width="450px" />
        <el-table-column label="商品编码" prop="code" width="150px" />
        <el-table-column label="商品类型" prop="goodsTypeName" width="150px" />
        <el-table-column label="商品图片" prop="picture">
          <template #default="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="scope.row.picture"
              :max-scale="7"
              :min-scale="0.2"
              preview-teleported
              :preview-src-list="[scope.row.picture]"
              fit="cover"
            />
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click.prevent="">
              详情
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="deleteRow(scope.row)"
            >
              删除
            </el-button>

            <el-button
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="goodsFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入商品编码" />
        </el-form-item>

        <el-form-item label="商品类型" prop="goodsTypeId">
          <template #default="scope">
            <el-select
              v-model="formData.goodsType"
              value-key="id"
              filterable
              remote
              reserve-keyword
              placeholder="请输入商品类型"
              style="width: 240px"
              @change="changeGoodsType"
            >
              <div
                v-infinite-scroll="fetchGoodsType"
                infinite-scroll-immediate="true"
                style="overflow: hidden; height: 400px"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                />
              </div>
              <template #loading>
                <svg class="circular" viewBox="0 0 50 50">
                  <circle class="path" cx="25" cy="25" r="20" fill="none" />
                </svg>
              </template>
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="商品图片" prop="picture">
          <el-input v-model="formData.picture" placeholder="请输入商品图片" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Goods",
  inheritAttrs: false,
});

import GoodsAPI, {
  GoodsForm,
  GoodsPageQuery,
  GoodsPageVO,
  GoodsType,
  GoodsTypeParam,
  ListItem,
} from "@/api/goods";
import { Search, Refresh, Plus, Delete } from "@element-plus/icons-vue";

const pageData = ref<GoodsPageVO[]>([]);

const loading = ref(false);

const pageNumRef = ref(1);

const queryParams = reactive<GoodsPageQuery>({
  pageNum: 1,
  pageSize: 3,
  code: "",
});

const dialog = reactive({
  title: "",
  visible: false,
});

const rules = reactive({
  name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  code: [{ required: true, message: "商品编码不能为空", trigger: "blur" }],
  picture: [{ required: true, message: "商品图片不能为空", trigger: "blur" }],
  goodsType: [{ required: true, message: "商品类型不能为空", trigger: "blur" }],
});

const goodsFormRef = ref(ElForm);

const formData = reactive<GoodsForm>({
  id: undefined,
  code: "",
  name: "",
  picture: "",
  goodsType: {} as GoodsType,
});

function handleQuery() {
  GoodsAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data;
      pageData.value.forEach((item) => {
        goodsTypeIdToName(item);
      });
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      console.log("");
    });
}

function resetHandleQuery() {
  queryParams.code = "";
}

function changeGoodsType(value: any) {
  formData.goodsType = value;
}

function handleCloseDialog() {
  goodsFormRef.value.resetFields();
  goodsFormRef.value.clearValidate();
  formData.id = undefined;
  dialog.visible = false;
}

function handleOpenDialog(goodsId?: number) {
  if (goodsId) {
    GoodsAPI.getFormData(goodsId).then((data) => {
      dialog.visible = true;
      dialog.title = "修改商品";
      nextTick(() => {
        Object.assign(formData, { ...data });
        formData.goodsType = { id: data.goodsTypeId } as GoodsType;
      });
    });
  } else {
    dialog.title = "新增商品";
    dialog.visible = true;
    formData.goodsType = undefined;
    pageNumRef.value = 1;
  }
}

const deleteRow = (row: GoodsPageVO) => {
  GoodsAPI.delete({ id: row.id } as GoodsPageQuery).then((data) => {
    pageData.value = data;
  });
};

const detailRow = (row: GoodsPageVO) => {
  GoodsAPI.delete({ id: row.id } as GoodsPageQuery).then((data) => {
    pageData.value = data;
  });
};

function handleSubmit() {
  goodsFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const goodsId = formData.id;
      if (goodsId) {
        GoodsAPI.update(goodsId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        GoodsAPI.save(formData)
          .then(() => {
            ElMessage.success("添加成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

onMounted(() => {
  handleQuery();
  fetchGoodsType();
});

const options = ref<ListItem[]>([]);

const fetchGoodsType = () => {
  console.log("----------", pageNumRef.value);
  GoodsAPI.getGoodsTypeList({
    pageNum: pageNumRef.value,
    pageSize: 10,
  } as GoodsTypeParam)
    .then((data) => {
      if (data.length > 0) {
        pageNumRef.value = pageNumRef.value + 1;
        options.value = [...options.value, ...data];
      }
    })
    .catch((error) => {
      console.log(error);
    });
};

const selectOnFocus = () => {
  pageNumRef.value = 1;
};

async function goodsTypeIdToName(goodsPageVO: GoodsPageVO) {
  let goodsType = await GoodsAPI.getGoodsType(goodsPageVO.goodsTypeId);
  goodsPageVO.goodsTypeName = goodsType.name;
}
</script>
